package misty.mispic.app.ui.thumb

import com.google.common.eventbus.Subscribe
import groovy.io.FileType
import groovy.transform.CompileStatic
import javafx.application.Platform
import javafx.beans.value.ChangeListener
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.geometry.Rectangle2D
import javafx.scene.control.Control
import javafx.scene.control.ScrollPane
import javafx.scene.control.Skin
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.FlowPane
import misty.mispic.app.event.EventBus
import misty.mispic.app.event.ThumbEvent

import java.nio.file.Path

/**
 * Created by Misty on 2015/1/24.
 */
@CompileStatic
class Thumb extends Control implements Initializable {
    private static List<String> EXTENSIONS = ['BMP', 'PCX', 'TIFF', 'GIF', 'JPG', 'JPEG', 'TGA', 'EXIF', 'FPX', 'SVG',
                                              'PSD', 'CDR', 'PCD', 'DXF', 'UFO', 'EPS', 'AI', 'PNG', 'HDRI', 'RAW']

    @FXML
    private ScrollPane mThumbRoot

    @FXML
    private FlowPane mThumbContent

    private Path lastPath

    Thumb() {
        sceneProperty().addListener({ obs, ov, nv ->
            if (ov) {
                EventBus.unregister(this)
            }
            if (nv) {
                EventBus.register(this)
            }
        } as ChangeListener)
    }

    @Override
    protected Skin createDefaultSkin() {
        return new ThumbSkin(this)
    }

    @Override
    void initialize(URL location, ResourceBundle resources) {
    }

    @Subscribe
    void showImages(ThumbEvent.Show show) {
        if (!show.path) {
            return
        }
        if (show.path.equals(lastPath)) {
            return
        }
        lastPath = show.path
        mThumbContent.children.clear()
        System.gc()
        new Thread({
            try {
                show.path.eachFile(FileType.FILES, {
                    def fn = it.fileName.toString()
                    def ext = fn.split(/\./)[-1]
                    if (EXTENSIONS.any { it.equalsIgnoreCase(ext) }) {
                        def img = new Image(it.toUri().toURL().toExternalForm(), 160, 120, true, true, true)
                        final def iv = new ImageView(img)
                        iv.with {
                            setViewport(new Rectangle2D(0, 0, 160, 120))
                            setFitWidth(160)
                            setFitHeight(120)
                            setPreserveRatio(true)
                            setSmooth(true)
                            setCache(true)
                        }
                        Platform.runLater {
                            mThumbContent.children << iv
                        }
                    }
                })
            } catch (ex) {
                ex.printStackTrace()
            }
        }).start()
    }
}
